<template>
    <div class="safety-list-container">
        <global-search @submitSearch="submitSearch" class="global-tool-search">
            <template slot="other-form">
                <el-form-item label="倍率">
                    <el-select v-model="form.rate" clearable filterable class="rate" placeholder="">
                        <el-option
                            v-for="item in rateList"
                            :key="item.value"
                            :label="item.name"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="死亡等级">
                    <el-select v-model="form.deathClass" filterable class="death-class" placeholder="">
                        <el-option
                            v-for="item in deathClassList"
                            :key="item.value"
                            :label="item.name"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="检索">
                    <el-input v-model="form.keyword" clearable placeholder="请输入病案号搜索"></el-input>
                </el-form-item>
            </template>
            <template slot="tool-box">
                <el-button type="text" @click="toExport" v-auth="{code: 200004004001}">
                    <svg-icon icon-class="export"/>
                    导出
                </el-button>
            </template>
        </global-search>
        <div class="tables-box">
            <el-table
                border
                :data="tableData"
                :max-height="tableHeight"
                tooltip-effect="light"
                row-key="medicalRecordID"
                style="width: 100%"
                :empty-text="emptyText"
                @sort-change="sortChange"
                @selection-change="handleSelectionChange">
                <el-table-column
                    show-overflow-tooltip
                    type="selection"
                    align="center"
                    width="30">
                </el-table-column>
                <el-table-column
                    show-overflow-tooltip
                    fixed
                    prop="date"
                    align="center"
                    type="index"
                    label="序号"
                    width="40">
                </el-table-column>
                <el-table-column
                    show-overflow-tooltip
                    fixed
                    prop="medicalRecordSign"
                    align="center"
                    label="病案号"
                    min-width="90">
                    <template slot-scope="scope">
                        <el-button type="text" :disabled="!viewInfoMonth(scope.row.dischargeDate)"
                                   @click="toInfo(scope.$index)">{{scope.row.medicalRecordSign}}
                        </el-button>
                    </template>
                </el-table-column>
                <el-table-column
                    show-overflow-tooltip
                    fixed
                    prop="patientName"
                    align="left"
                    label="患者姓名"
                    min-width="65">
                </el-table-column>
                <el-table-column
                    show-overflow-tooltip
                    prop="dischargeDate"
                    align="center"
                    sortable="custom"
                    label="出院时间"
                    min-width="85">
                    <template slot-scope="scope">
                        {{scope.row.dischargeDate.substring(0, 10)}}
                    </template>
                </el-table-column>
                <el-table-column
                    show-overflow-tooltip
                    prop="hospitalTime"
                    align="center"
                    sortable="custom"
                    label="住院次数"
                    min-width="80">
                </el-table-column>
                <el-table-column
                    show-overflow-tooltip
                    prop="totalFee"
                    align="center"
                    sortable="custom"
                    label="住院总费用"
                    min-width="95">
                    <template slot-scope="scope">
                        {{scope.row.totalFee | getMoneyNum}}
                    </template>
                </el-table-column>
                <el-table-column
                    show-overflow-tooltip
                    align="center"
                    label="组均住院费用">
                    <el-table-column
                        show-overflow-tooltip
                        prop="drgAvgFee"
                        align="center"
                        label="院内"
                        min-width="80">
                        <template slot="header" slot-scope="scope">
                            <el-tooltip class="item" effect="light" content="计算院内该组数据3年内的平均值" placement="top">
                                <span>院内</span>
                            </el-tooltip>
                        </template>
                        <template slot-scope="scope">
                            <span v-if="scope.row.state === '已入组' || scope.row.drgAvgFee">{{scope.row.drgAvgFee | getMoneyNum}}</span>
                            <span v-else>/</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        show-overflow-tooltip
                        prop="drgStandardFee"
                        align="center"
                        sortable="custom"
                        label="区域"
                        min-width="80">
                        <template slot-scope="scope">
                            <span v-if="scope.row.state === '已入组' || scope.row.drgStandardFee">{{scope.row.drgStandardFee | getMoneyNum}}</span>
                            <span v-else>/</span>
                        </template>
                    </el-table-column>
                </el-table-column>
                <el-table-column
                    show-overflow-tooltip
                    prop="drgIncome"
                    sortable="custom"
                    align="right"
                    label="DRG盈亏"
                    min-width="85">
                    <template slot-scope="scope">
                        {{scope.row.drgIncome | getMoneyNum}}
                    </template>
                </el-table-column>
                <el-table-column
                    show-overflow-tooltip
                    prop="hospitalDays"
                    align="center"
                    sortable="custom"
                    label="住院日"
                    min-width="65">
                </el-table-column>
                <el-table-column
                    show-overflow-tooltip
                    align="center"
                    label="组均住院日">
                    <el-table-column
                        show-overflow-tooltip
                        prop="drgAvgDays"
                        align="center"
                        label="院内"
                        min-width="50">
                        <template slot="header" slot-scope="scope">
                            <el-tooltip class="item" effect="light" content="计算院内该组数据3年内的平均值" placement="top">
                                <span>院内</span>
                            </el-tooltip>
                        </template>
                        <template slot-scope="scope">
                            <span v-if="scope.row.state === '已入组'">{{scope.row.drgAvgDays}}</span>
                            <span v-else>{{scope.row.drgAvgDays ? scope.row.drgAvgDays : '/'}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        show-overflow-tooltip
                        prop="drgStandardDays"
                        align="center"
                        sortable="custom"
                        label="区域"
                        min-width="55">
                        <template slot-scope="scope">
                            <span v-if="scope.row.state === '已入组'">{{scope.row.drgStandardDays}}</span>
                            <span v-else>{{scope.row.drgStandardDays ? scope.row.drgStandardDays : '/'}}</span>
                        </template>
                    </el-table-column>
                </el-table-column>
                <el-table-column
                    show-overflow-tooltip
                    prop="drgCode"
                    align="center"
                    label="分组编码"
                    min-width="70">
                </el-table-column>
                <el-table-column
                    show-overflow-tooltip
                    prop="drgName"
                    align="left"
                    label="分组名称"
                    min-width="100">
                </el-table-column>
                <el-table-column
                    show-overflow-tooltip
                    prop="type"
                    align="center"
                    label="类型"
                    min-width="65">
                    <template slot-scope="scope">
                        <span :class="{'status-blue': scope.row.type === 1, 'status-red': scope.row.type === 2}">{{scope.row.type | getType}}</span>
                    </template>
                </el-table-column>
                <el-table-column
                    show-overflow-tooltip
                    prop="riskLevel"
                    align="center"
                    label="风险等级"
                    min-width="80">
                    <template slot-scope="scope">
                        {{scope.row.riskLevel | getRiskLevel}}
                    </template>
                </el-table-column>
            </el-table>
            <pagination v-show="tableData.length > 0" :total="total" :page.sync="currentPage" :limit.sync="pageSize"
                        @pagination="changePage"/>
        </div>
    </div>
</template>

<script>
    import {getSortString, viewInfoMonth, getMoneyNum} from '@/utils/filters'
    import {dataAnalysisList, exportAnalysisList} from '@/api/data-analysis/global'
    import FileSaver from 'file-saver'
    import ExcelJS from 'exceljs'

    export default {
        name: 'index',
        data () {
            return {
                // 搜索条件
                form: {
                    rate: 0,
                    deathClass: 0,
                    keyword: '',
                    resident: ''
                },
                // 当前页
                currentPage: 1,
                // 每页数量
                pageSize: 20,
                // 表格高度
                tableHeight: 0,
                // 全部表格数据
                tableData: [],
                // 数据总数
                total: 0,
                // 倍率列表
                rateList: [{
                    name: '全部',
                    value: 0
                }, {
                    name: '低倍率',
                    value: 1
                }, {
                    name: '高倍率',
                    value: 2
                }],
                // 死亡等级列表
                deathClassList: [{
                    name: '无',
                    value: 0
                }, {
                    name: '全部死亡',
                    value: 1
                }, {
                    name: '低风险组死亡',
                    value: 2
                }, {
                    name: '中低风险组死亡',
                    value: 3
                }, {
                    name: '中高风险组死亡',
                    value: 4
                }, {
                    name: '高风险组死亡',
                    value: 5
                }],
                // 全局搜索内容，用于翻页等不传参时使用数据
                globalForm: {},
                // 排序字段
                sortMap: {},
                // 排序方式
                sortType: '',
                // 选中的数据
                multipleSelection: [],
                // 空数据时显示的文本内容
                emptyText: '暂无数据',
                // 使用储存的数据，不去请求
                useStore: false,
                // 导出的全部数据
                allexportData: []
            }
        },
        created () {
            // tags判断入口是否从选项卡进入
            this.useStore = this.$route.query.tags === 'tags'
            this.initPage()
            // 头部40 + 快捷标签30 + 面包屑30 + 搜索框42 + 分页64 + 底部padding10 + 表格上面和灰色背景的空白10px
            let height = document.documentElement.clientHeight - 100 - 42 - 64 - 10 - 10
            this.tableHeight = height > 108 ? height : 108
        },
        mounted () {
            let searchHeight = document.getElementsByClassName('global-tool-search')[0].offsetHeight
            if (searchHeight > 42) {
                let height = document.documentElement.clientHeight - 100 - searchHeight - 64 - 10 - 10
                this.tableHeight = height > 108 ? height : 108
            }
            // 白色背景高度
            document.getElementsByClassName('tables-box')[0].style.height = this.tableHeight + 64 + 10 + 'px'
            // 分页组件位置，不能使用bottom = 0，当位置发生变化时会出错
            document.getElementsByClassName('pagination-container')[0].style.top = this.tableHeight + 10 + 'px'
            window.onresize = () => {
                let height = document.documentElement.clientHeight - 100 - searchHeight - 64 - 10 - 10
                this.tableHeight = height > 108 ? height : 108
                document.getElementsByClassName('tables-box')[0].style.height = this.tableHeight + 64 + 10 + 'px'
                document.getElementsByClassName('pagination-container')[0].style.top = this.tableHeight + 10 + 'px'
            }
        },
        methods: {
            viewInfoMonth,
            /**
             * 初始化页面参数
             */
            initPage () {
                let query = JSON.parse(JSON.stringify(this.$store.state.search.searchForm[this.$route.name]))
                if (query) {
                    this.form.rate = query.rate
                    this.form.deathClass = query.deathClass
                    this.form.keyword = query.keyword
                    this.form.resident = query.resident
                    this.currentPage = query.pageIndex || 1
                    this.pageSize = query.pageSize || 20
                }
            },
            /**
             * 翻页
             */
            changePage () {
                this.submitSearch()
            },
            /**
             * 提交查询
             * @param form 筛选条件
             */
            submitSearch (form) {
                let data = form || this.globalForm
                this.globalForm = data
                let params = {
                    ...data,
                    ...this.form,
                    department: data.department || this.$route.query.department,
                    depName: data.depName || this.$route.query.depName,
                    pageSize: this.pageSize,
                    pageIndex: this.currentPage,
                    orderBy: this.sortType
                }
                this.tableData = []
                this.getDataAnalysisList(params)
                this.setGetStore(this.$route.name, params)
            },
            /**
             * 查询费用列表
             * @param params 请求参数
             */
            getDataAnalysisList (params) {
                let riskLevel = 0
                let deathState = 0
                if (params.deathClass) {
                    deathState = 1
                    riskLevel = params.deathClass - 1
                }
                params.riskLevel = riskLevel
                params.deathState = deathState
                this.emptyText = '加载中...'
                if (this.getSession(this.$route.name, 'dataAnalysisList') && this.useStore) {
                    this.useStore = false
                    let res = this.getSession(this.$route.name, 'dataAnalysisList')
                    this.emptyText = '暂无数据'
                    if (res.code.toString() === '200') {
                        this.total = res.data.total
                        this.tableData = res.data.rows
                        this.sortMap = res.data.maps
                    }
                } else {
                    dataAnalysisList(params).then(res => {
                        this.useStore = false
                        this.setSession(this.$route.name, {dataAnalysisList: res})
                        this.emptyText = '暂无数据'
                        if (res.code.toString() === '200') {
                            this.total = res.data.total
                            this.tableData = res.data.rows
                            this.sortMap = res.data.maps
                        }
                    }).catch(() => {
                        this.emptyText = '暂无数据'
                    })
                }
            },
            /**
             * 选中事件
             */
            handleSelectionChange (val) {
                this.multipleSelection = val
            },
            /**
             * 获取选中id
             */
            getSelectId () {
                let arr = []
                if (this.multipleSelection.length) {
                    this.multipleSelection.forEach(item => {
                        arr.push(item.medicalRecordID)
                    })
                    return arr
                } else {
                    return false
                }
            },
            /**
             * 导出数据列表
             */
            toExport () {
                let params = JSON.parse(JSON.stringify(this.$store.state.search.searchForm[this.$route.name]))
                params.idList = this.getSelectId() || []
                this.$store.dispatch('app/UpdateLoadingText', '0%')
                this.$store.dispatch('app/UpdateIsExport', true)
                this.$store.dispatch('app/UpdateLoading', true)
                params.pageIndex = 1
                params.pageSize = 1000
                this.allexportData = []
                this.sendRequest(params)
            },
            /**
             * 发送请求
             * @param params 请求参数
             */
            sendRequest (params) {
                let allIndex = Math.ceil(this.total / 1000)
                exportAnalysisList(params).then(res => {
                    if (res.code.toString() === '200') {
                        this.$store.dispatch('app/UpdateLoadingText', parseInt(params.pageIndex / allIndex * 95) + '%')
                        this.allexportData = this.allexportData.concat(res.data)
                        if (params.pageIndex < allIndex) {
                            this.sendRequest({...params, pageIndex: params.pageIndex + 1})
                        } else {
                            this.exportDataList('费用情况数据列表', this.allexportData)
                        }
                    } else {
                        this.$store.dispatch('app/UpdateIsExport', false)
                        this.$store.dispatch('app/UpdateLoading', false)
                        this.$message.error('导出失败')
                    }
                }).catch(() => {
                    this.$store.dispatch('app/UpdateIsExport', false)
                    this.$store.dispatch('app/UpdateLoading', false)
                    this.$message.error('导出失败')
                })
            },
            /**
             * 导出excel表头
             */
            getHeader () {
                return [{
                    key: 'index', width: 10
                }, {
                    key: 'medicalRecordSign', width: 16
                }, {
                    key: 'patientName', width: 12
                }, {
                    key: 'dischargeDate', width: 16
                }, {
                    key: 'hospitalTime', width: 12
                }, {
                    key: 'totalFee', width: 16
                }, {
                    key: 'drgAvgFee', width: 16
                }, {
                    key: 'drgStandardFee', width: 16
                }, {
                    key: 'drgIncome', width: 24
                }, {
                    key: 'hospitalDays', width: 12
                }, {
                    key: 'drgAvgDays', width: 12
                }, {
                    key: 'drgStandardDays', width: 12
                }, {
                    key: 'drgCode', width: 16
                }, {
                    key: 'drgName', width: 32
                }, {
                    key: 'type', width: 16
                }, {
                    key: 'riskLevel', width: 16
                }]
            },
            /**
             * 导出列表excel
             */
            exportDataList (name, data) {
                let workbook = new ExcelJS.Workbook()
                workbook.creator = 'lyliang'
                workbook.views = [{
                    x: 0,
                    y: 0,
                    firstSheet: 0,
                    activeTab: 1,
                    visibility: 'visible'
                }]
                let worksheet = workbook.addWorksheet('Sheet1')
                /* eslint-disable */
                worksheet.getRow(1).values = ['序号', '病案号', '患者姓名', '出院时间', '住院次数', '住院总费用', '组均住院费用', , 'DRG盈亏', '住院日', '组均住院日', , '分组编码', '分组名称', '类型', '风险等级']
                /* eslint-enable */
                worksheet.getRow(2).values = ['序号', '病案号', '患者姓名', '出院时间', '住院次数', '住院总费用', '院内', '区域', 'DRG盈亏', '住院日', '院内', '区域', '分组编码', '分组名称', '类型', '风险等级']
                worksheet.columns = this.getHeader()
                worksheet.mergeCells('A1:A2')
                worksheet.mergeCells('B1:B2')
                worksheet.mergeCells('C1:C2')
                worksheet.mergeCells('D1:D2')
                worksheet.mergeCells('E1:E2')
                worksheet.mergeCells('F1:F2')
                worksheet.mergeCells('I1:I2')
                worksheet.mergeCells('J1:J2')
                worksheet.mergeCells('M1:M2')
                worksheet.mergeCells('N1:N2')
                worksheet.mergeCells('O1:O2')
                worksheet.mergeCells('P1:P2')
                worksheet.mergeCells('G1:H1')
                worksheet.mergeCells('K1:L1')
                for (let i = 0; i < data.length; i++) {
                    data[i].index = i + 1
                    data[i].dischargeDate = data[i].dischargeDate.substring(0, 10)
                    data[i].totalFee = getMoneyNum(data[i].totalFee)
                    data[i].drgAvgFee = data[i].state === '已入组' || data[i].drgAvgFee ? getMoneyNum(data[i].drgAvgFee) : '/'
                    data[i].drgStandardFee = data[i].state === '已入组' || data[i].drgStandardFee ? getMoneyNum(data[i].drgStandardFee) : '/'
                    data[i].drgIncome = getMoneyNum(data[i].drgIncome)
                    data[i].drgAvgDays = data[i].state === '已入组' || data[i].drgAvgDays ? data[i].drgAvgDays : '/'
                    data[i].drgStandardDays = data[i].state === '已入组' || data[i].drgStandardDays ? data[i].drgStandardDays : '/'
                    data[i].type = this.$options.filters['getType'](data[i].type)
                    data[i].riskLevel = this.$options.filters['getRiskLevel'](data[i].riskLevel)
                    worksheet.addRow(data[i])
                    worksheet.getRow(i + 1).alignment = {vertical: 'middle', horizontal: 'center'}
                    let rate = parseInt((i + 1) / data.length * 0.03 * 100 + 95) + '%'
                    this.$store.dispatch('app/UpdateLoadingText', rate)
                }
                worksheet.getRow(data.length + 1).alignment = {vertical: 'middle', horizontal: 'center'}
                worksheet.getRow(data.length + 2).alignment = {vertical: 'middle', horizontal: 'center'}
                worksheet.getColumn('drgName').alignment = {wrapText: true, vertical: 'middle', horizontal: 'left'}
                worksheet.getColumn('drgCode').alignment = {wrapText: true, vertical: 'middle', horizontal: 'center'}
                workbook.xlsx.writeBuffer().then(data => {
                    this.$store.dispatch('app/UpdateLoadingText', '99%')
                    let blob = new Blob([data], {type: 'EXCEL_TYPE'})
                    FileSaver.saveAs(blob, `${this.parseTime(new Date().getTime())} ${name}.xlsx`)
                    this.$store.dispatch('app/UpdateLoadingText', '100%')
                    this.$store.dispatch('app/UpdateIsExport', false)
                    this.$store.dispatch('app/UpdateLoading', false)
                })
            },
            /**
             * 排序修改
             * @param colData.prop 排序参数
             * @param colData.order 正序倒序 ascending 升序 descending 降序 null 不排序默认
             */
            sortChange (colData) {
                this.sortType = getSortString(colData, this.sortMap)
                this.tableData = []
                this.currentPage = 1
                this.submitSearch()
            },
            /**
             * 前往病案详情
             * @param index 索引
             */
            toInfo (index) {
                // 获取当前页面筛选条件
                let query = JSON.parse(JSON.stringify(this.$store.state.search.searchForm[this.$route.name]))
                // 获取数据索引（详情页每页是1条，即是详情页页码）
                let pageIndex = (this.currentPage - 1) * this.pageSize + index + 1
                this.$store.dispatch('search/coverSearchFormItem', {
                    pageName: 'ExpensesListInfo',
                    query: {...query, pageIndex}
                })
                this.$router.push({name: 'ExpensesListInfo'})
            }
        },
        filters: {
            getMoneyNum,
            getType (val) {
                switch (val) {
                case 0:
                    return '正常'
                case 1:
                    return '低倍率'
                case 2:
                    return '高倍率'
                }
            },
            getRiskLevel (val) {
                switch (val) {
                case 0:
                    return ''
                case 1:
                    return '低'
                case 2:
                    return '中低'
                case 3:
                    return '中高'
                case 4:
                    return '高'
                }
            }
        },
        beforeDestroy () {
            window.onresize = null
        }
    }
</script>

<style scoped lang="scss">
    .safety-list-container {
        .el-form-item--mini.el-form-item {
            margin-bottom: 10px;
        }
        .rate {
            width: 100px;
        }
        .death-class {
            width: 130px;
        }
        .tables-box {
            background: #fff;
            padding: 10px 10px 0;
            position: relative;
            .pagination-container {
                position: absolute;
                top: 0;
                right: 0;
            }
        }
    }
</style>
